package asf.forms
{
	import asf.core.Application;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.utils.getDefinitionByName;
	
	dynamic public class Form extends FormFields
	{
		private var app:Application;
		private var _view:Sprite;
		private var container:Sprite;
		
		public function Form( p_raw:XML, p_app:Application, sourceXML:XML )
		{
			super( p_raw, sourceXML );
			container = new Sprite( );
			
			x = parseFloat( sourceXML.@marginLeft );
			y = parseFloat( sourceXML.@marginTop );
			
			this.app = p_app;
		}
		
		public function get view( ):Sprite
		{
			if( _view == null )
			{
				var c:Class = getDefinitionByName( raw.@viewClass ) as Class;
				_view = new c( ) as Sprite;
			}
			
			return _view;
		}
		
		public function addFields( ):void
		{
			var field:FormField;
			var fields:Array = getFields( );
			
			for each( field in fields )
			{
				this.container.addChild( field.view as DisplayObject );
			}
			
			this.view.addChild( container );
		}
		
		public function get id( ):String
		{
			return raw.@id || raw.id;
		}
		
		public function get srcPath( ):String
		{
			return app.getParsedValueOf( raw.@src || raw.src );
		}
		
		public override function dispose( ):void
		{
			var field:FormField;
			var fields:Array = getFields( );
			
			for each( field in fields )
			{
				if( this.container.contains( field.view as DisplayObject ) )
				{
					this.container.removeChild( field.view as DisplayObject );
				}
				
				field.dispose( );
			}
			
			this.view.removeChild( this.container );
			this.container = null;
			
			this.app = null;
			this.source = null;
			
			try
			{
				( view as Object ).dispose( );
			}
			catch( e:Error ){ }
			
			super.dispose( );
		}
		
		public function get y( ):Number
		{
			return this.container.y;
		}
		
		public function set y( value:Number ):void
		{
			this.container.y = value;
		}
		
		public function get x( ):Number
		{
			return this.container.x;
		}
		
		public function set x( value:Number ):void
		{
			this.container.x = value;
		}
		
		public function toString( ):String
		{
			return "[object Form: '" + id + "' ]";
		}
	}
}